<?php
/**
 * Library to modify entries in the config file
 *
 * @copyright inovia
 */
class ConfigFile{
  private $path;
  private $file = null;
  
  /**
   * Constructor
   */     
  public function __construct($path="config.php"){
    $this->path = $path;
  
    if(file_exists($this->path)){
      $this->file = file($this->path); //opens a file handler
      if($this->file==null) echo "blem";
    }
  }
  
  /**
   * Checks if the var is an array in the file
   */     
  public function isArrayVar($varName){
    foreach($this->file as $line){
      if($line[0] == "$"){
        $tabLine = explode(" = ",$line);
        if(str_replace(" ","",$tabLine[0])== $varName) {  //if i found the searched variable
          if(substr(rtrim($tabLine[1]), 0, 5) == "Array") return true;
          else return false;
        }
      }
    }
  }
  
  
  /**
   * Sets a var 
   * Can be a simple var, an array definition in a single line or an array definition in multiple lines   
   * or an array of array in multiline definition   
   * If simple var, $array = ("Value of the var");  
   * If array in multiple lines : 
   * $array = Array(
   *  "key1" => "value1",
   *  "key2" => "value1",
   * )      
   * If an array of array in multiline : 
   * $array = Array(
   *  "key1" => Array("value1.1","value1.2"),
   *  "key2" => Array("value2.1","value2.2"),
   * )     
   * 
   * @param string $varName the name of the var (example : "\$configGroups")   
   * @param mixed $array the value of the var string for simple var and primary types vars Array for Array var
   * @param bool $write if true the method writes down in the file
   * @return true if success write, false else   
   *      
   * @todo objects definition if needed  
   */        
  public function setVar($varName,$array,$write=false){
    $numLine = -1;
    foreach($this->file as $key=>$value) {
      $this->file[$key]=trim($value);
    }
    
    foreach($this->file as $line){
      $numLine++;
      if(isset($line[0]) && $line[0] == "$"){
        $tabLine = explode(" = ",$line);
        if(str_replace(" ","",$tabLine[0])== $varName) {  //if i found the searched variable
          if(substr(rtrim($tabLine[1]), 0, 5) == "Array") {
          
            //******************* Array var **************************//
            //------ single line case --------//
            if($this->isSingleLineArray($line)){
            $line2 = strval($varName)." = Array(";
            foreach ($array as $val){
              $line2 .= "\"".$val."\",";
            }
            $line2 = substr($line2, 0, strlen($line2)-1);  //deletes the last ,
            $line2 .= ");//endArray";
            $this->file[$numLine] = $line2;
            
            
            //------ multiline case --------//
            }else{
              $linesNeeded = count($array)+2;                     //how many lines do i need to write down the Array var
              $linesUsed   = $this->arraySize($numLine);          //retrieves the size of the array in the file
              $this->eraseLines($numLine,$numLine+$linesUsed);    //erases the lines of the Array
              if($linesNeeded > $linesUsed){                      //if i need more space
                $this->addSpace($numLine+$linesUsed,$linesNeeded-$linesUsed);
              }
              //copy the Array in this->file
              $this->file[$numLine] = strval($varName)." = Array(";
              $i = $numLine+1;
              foreach($array as $key => $value){
                //if we have an array of array
                if(is_array($value)){
                  $valuestring = 'Array(';
                  foreach($value as $valuevalue){
                      $valuestring .= "\"".strval($valuevalue)."\",";
                  }
                  $valuestring = substr($valuestring, 0, strlen($valuestring)-1);   //deletes the last ,
                  $valuestring .= ')';
                  $this->file[$i] = "\"".strval($key)."\" => ".$valuestring.",";
                  
                //if it's a simple key / value
                }else{
                  $this->file[$i] = "\"".strval($key)."\" => \"".$value."\",";
                }
                $i++;
              }
              $this->file[$i-1] = substr($this->file[$i-1], 0, strlen($this->file[$i-1])-1);   //deletes the last ,
              $this->file[$i] = ");//endArray";
              
                                                         
            }
            //writes down the file if required
            if($write) $this->write($this->file);
            return true;   
          }else{
            //******************* Simple var **************************//
            $this->file[$numLine] = strval($varName)." = \"".strval($array)."\";";
            
            //writes down the file if required
            if($write) $this->write($this->file);
              return true;
            }
        }
      }
    }
  }
  
  /**
   * Adds space (of $size size) starting to line number $end
   */     
  protected function addSpace($end,$size){
    $totalSize = count($this->file);
    for($i = $totalSize+1;$i>=$end;$i--){
      $this->file[$i+$size] = $this->file[$i];
    }
  }
  
  /**
   * Counts the number of lines of the multiline Array definition
   *
   */
  protected function arraySize($startLine){
    $numberLines = 1;
    while(true){
      $line = rtrim($this->file[$startLine+$numberLines-1]);
      if(substr($line, -12) == ");//endArray"){  //end of array
        return $numberLines;
      }
      $numberLines++;
    }
  }
  
  /**
   * Deletes lines between start and end (both included)
   */     
  protected function eraseLines($start,$end){
    for($i=$start;$i < $end;$i++){
      $this->file[$i] = "";
    }
  }

  /**
   * Returns if the Line contains a single line array definition
   */     
  public function isSingleLineArray($line){
    $line = rtrim($line); //cleans string end
    if(substr($line, -12) == ");//endArray" )return true;
    else return false;
  }


  /**
   * Writes down array elements in the file
   * 
   */        
  public function write(&$array){       
    $size = count($array);
    $f=@fopen($this->path, 'w');
    for ($i=0;$i<=$size;$i++){
      @fwrite($f,$array[$i]."\n");
      if($array[$i] == "?>") break;
    }
    @fclose($f);
  }


}
?>
